package com.gitee.wsl.collections.iterator

import com.gitee.wsl.collections.iterator.api.MutableMapEntry
import com.gitee.wsl.collections.iterator.api.MutableMapEntryIterator


class MutableMapFunEntry<K, V>(
    override val key: K,
    private val getter: (K) -> V,
    private val setter: (K, V) -> Unit
) : MutableMapEntry<K, V> {

    override val value: V
        get() {
            return getter(key)
        }

    override fun setValue(newValue: V): V {
        val ret = value
        setter(key, newValue)
        return ret
    }
}



@Suppress("UNCHECKED_CAST")
class MutableMapFunIterator<K, V>(
    private val keyIterator: MutableIterator<K>,
    private val getter: (K) -> V,
    private val setter: (K, V) -> Unit,
    private val eraser: (K) -> Unit
) : MutableMapEntryIterator<K, V> {
    var key: Any? = null

    override fun hasNext() = keyIterator.hasNext()

    override fun next(): MutableMap.MutableEntry<K, V> {
        key = keyIterator.next()
        return MutableMapFunEntry(key as K, getter, setter)
    }

    override fun remove() {
        keyIterator.remove()
        eraser(key as K)
    }
}
